"""
可迭代对象: Python中任意的对象，只要它定义了可以返回一个迭代器的__iter__方法。
"""

# https://www.jianshu.com/p/fe4845e853ae

"""
一个实现了__iter__方法和__next__方法的对象，就是迭代器
"""




class MyList(object):
    """自定义的一个可迭代对象"""
    def __init__(self):
        self.items = []
    def add(self, val):
        self.items.append(val)
    def __iter__(self):
        myiterator = MyIterator(self)
        return myiterator

class MyIterator(object):
    """自定义的迭代器"""
    def __init__(self, mylist):
        self.mylist = mylist
        # current用来记录当前访问到的位置
        self.current = 0

    def __next__(self):
        if self.current < len(self.mylist.items):
            item = self.mylist.items[self.current]
            self.current += 1
            return item
        else:
            raise StopIteration
    def __iter__(self):
        return self


aa = MyList()
aa.add(23)
aa.add(44)

for i in aa:
    print(i)



"""在函数内部使用yield就叫做生成器"""
# https://www.jianshu.com/p/58bfc21bbd81
def gen():
    res = yield 12
    print(res)
    return 'done'

gen = gen()
print('next', next(gen))
gen.send('aaaa')
print('next', next(gen))


